import { Alert, Card, Cascader, Col, Row, Tabs } from 'antd'
import React, { useState, useEffect } from 'react'
import PageBreadcrumb from '../../components/PageBreadcrumb'
import { getCategories } from "../../api/categories.js"
import { getCategoriesParam } from "../../api/params.js";
import TablePane from './TablePane'
import AddOrEditParam from './AddOrEditParam';
import AddAttrVals from './AddAttrVals';

const { TabPane } = Tabs;

const ParamsList = () => {

  const [loading, setLoading] = useState(false) // 加载
  const [selectedKeys, setSelectedKeys] = useState([])
  const [activeKey, setActiveKey] = useState("many")
  const [cateList, setCateList] = useState([])
  const [manyData, setManyData] = useState([]); //商品参数
  const [onlyData, seOnlyDatat] = useState([]); //商品属性
  const [cateId, seCateId] = useState(null); // 当前选中的商品分类ID

  const [isAddOrEdit, setIsAddOrEdit] = useState(false) // 控制对话框的显示和隐藏
  const [attrInfo, setAttrInfo] = useState({}) // 当前行数据
  const [titleText, setTitleText] = useState("");
  const [isAddAttr, setIsAddAttr] = useState(false) // 控制对话框的显示和隐藏

  useEffect(() => {
    getCateList()
  }, [])

  useEffect(() => {
    if (selectedKeys.length === 3) {
      getParamsData()
    }
  }, [selectedKeys, activeKey])

  // 获取商品分类
  const getCateList = async () => {
    const data = await getCategories();
    setCateList(data)
  };


  // 获取参数列表数据
  const getParamsData = async () => {
    if (cateId) {
      setLoading(true)
      // 根据所选分类ID和当前所处的面板获取对应的参数
      const data = await getCategoriesParam(cateId, activeKey).finally(() => {
        setLoading(false)
      });

      data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
      });

      if (activeKey === "many") {
        setManyData(data)
      } else {
        seOnlyDatat(data)
      }
    }
  };

  // 选择商品分类
  const cateChange = (value) => {
    if (value.length !== 3) {
      setSelectedKeys([])
      setManyData([])
      seOnlyDatat([])
    } else {
      setSelectedKeys(value)
      seCateId(value[2])
    }
  };

  // tab页签点击事件
  const handleTabClick = (key) => {
    setActiveKey(key)
  };

  // 添加attr_vals
  const openAddAttr = (row) => {
    setIsAddAttr(true)
    if (activeKey === "many") {
      setTitleText("参数")
    } else {
      setTitleText("属性")
    }
    setAttrInfo(row)
  }

  // 关闭添加/编辑对话框
  const hideAddAttr = (type) => {
    setAttrInfo({})
    setIsAddAttr(false)
    setTitleText("")
    if (type) {
      getParamsData()
    }
  }

  // 点击添加/编辑按钮
  const openAddOrEdit = (row) => {
    setIsAddOrEdit(true)
    if (activeKey === "many") {
      setTitleText("动态参数")
    } else {
      setTitleText("静态属性")
    }
    setAttrInfo(row)
  };

  // 关闭添加/编辑对话框
  const hideAddOrEdit = (type) => {
    setAttrInfo({})
    setIsAddOrEdit(false)
    setTitleText("")
    if (type) {
      getParamsData()
    }
  }

  return (
    <>
      <PageBreadcrumb>
        <span>商品管理</span>
        <span>参数列表</span>
      </PageBreadcrumb>

      <Card>
        <Alert message="注意：只允许为第三级分类设置相关参数！" type="warning" showIcon />
        <Row>
          <Col>
            <label>选择商品分类：</label>
            <Cascader
              fieldNames={{
                label: 'cat_name',
                value: 'cat_id',
                children: 'children',
              }}
              value={selectedKeys}
              options={cateList}
              onChange={cateChange}
              style={{ width: '250px' }}
              expandTrigger="hover"
              allowClear={true}
            />
          </Col>
        </Row>

        <Tabs activeKey={activeKey} onChange={handleTabClick}>
          <TabPane tab="动态参数" key="many">
            <TablePane
              loading={loading}
              pageText="参数"
              data={manyData}
              cateId={cateId}
              activeKey={activeKey}
              setData={openAddOrEdit}
              onEvent={getParamsData}
              saveAttr={openAddAttr}
            />
          </TabPane>

          <TabPane tab="静态属性" key="only">
            <TablePane
              loading={loading}
              pageText="属性"
              data={onlyData}
              cateId={cateId}
              activeKey={activeKey}
              setData={openAddOrEdit}
              onEvent={getParamsData}
              saveAttr={openAddAttr}
            />
          </TabPane>
        </Tabs>
      </Card>
      <AddOrEditParam
        visible={isAddOrEdit}
        attrInfo={attrInfo}
        titleText={titleText}
        activeKey={activeKey}
        cateId={cateId}
        onHide={hideAddOrEdit}
      />
      <AddAttrVals
        visible={isAddAttr}
        attrInfo={attrInfo}
        titleText={titleText}
        cateId={cateId}
        onHide={hideAddAttr}
      />
    </>
  )
}

export default ParamsList